/**
 * @Author:卿雨欣
 * @Date:2020/7/3
 * @Description:这是产品买入页面的金额输入框以及成分产品购买明细
 */
import React,{Component} from "react";
import "../../../access/images/success.png"
import {
    InputItem,
    List,
    Toast,
    WhiteSpace,
    Modal,
    Checkbox,
    Button,
    Radio,
    ActionSheet,
    Result,
    Card, Tag
} from 'antd-mobile';
import axios from "axios";
import {getCookieId, getCookieRisk} from "../../Login/Component_Login/GetCookie";
import {message} from "antd";
import {Link} from "react-router-dom";
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let moneyKeyboardWrapProps;
let wrapProps;
var ss = false;
const AgreeItem = Checkbox.AgreeItem;

const Item = List.Item;
const alert = Modal.alert; //购买明细弹窗
const prompt = Modal.prompt;
export default class FormBuyBack extends Component{
    constructor(props) {
        super(props);
        this.state={
            amount:"",//赎回金额
            allAmount:0,
            backAll:false,
            redBoolen:false,//判断待支付金额什么时候变为红色
            combinatiobShares:[],//组合的成分产品列表
            trialCalculationList:[],//成分产品试算金额列表
            trial:false,//false展示初始的成分产品列表，true展示试算金额列表
            totalRedemptionIndex:0,//是否全部赎回，1全部，0部分
        }
        this.buyBack.bind(this);
        this.backAll.bind(this);
        this.validateMoney.bind(this);
    }
    //成分产品购买试算以及验证输入金额是否满足起购金额
    validateMoney = (rule, value, callback) => {
        if(value===""){
            this.setState({
                backAll:false,
            })
        }
        if(value === this.state.allAmount){
            this.setState({
                totalRedemptionIndex:1,
            })
        }else{
            this.setState({
                totalRedemptionIndex:0,
            })
        }
        //满足起购金额，进行金额试算'
        if (value && value<=this.state.allAmount) {
            callback();
            axios({
                method:"GET",
                url:"http://39.101.141.248:9527/transaction/trialCalculation",
                params:{
                    comBaseId:this.props.comBaseId,
                    amount:value,
                },
            }).then(res=>{
                if(res.data.code === 200){
                    this.setState({
                        amount:value,
                        redBoolen:true,
                        backAll:false,
                        trial:true,
                        trialCalculationList:res.data.trialCalculationList,
                        /*realTotalAmount:res.data.realTotalAmount*/
                    })
                }
            }).catch(error=>{
                console.log(error);
            });
        } else { //不满足起购金额，提示错误
            /* Toast.info("购买金额不得低于100,00万元")  一键买入组合时，您的购买金额会自动根据管理人的持仓配比和在途交易调整至最合适的配比。*/
            callback(new Error('At least four characters for account'));
            this.setState({
                amount:"",
                redBoolen:false,
                trial:false,
            })
        }
    }
    //获取页面数据，成分产品
    componentWillMount() {
        axios({
            method:"GET",
            url:"http://39.101.141.248:9527/transaction/verifyRedemptionAmount",
            params:{
                userId:getCookieId(),
                comBaseId:this.props.comBaseId,
            },
        }).then(res=>{
            if(res.data.code === 200){
                console.log(res.data)
                this.setState({
                    allAmount:res.data.RedeemableAmount,
                })
            }
        }).catch(error=>{
            console.log(error);
        });
        //成分产品列表
        axios({
            method:"GET",
            url:"http://39.101.141.248:9527/combinationShare/getCombinationShareInfo",
            params:{comBaseId:this.props.comBaseId/*this.props.comBaseId*/},
        }).then(res=>{
            if(res.data.code === 200){
                this.setState({
                    combinatiobShares:res.data.combinatiobShares
                })
            }
        }).catch(error=>{
            console.log(error);
        });
    }
    //全部赎回
    backAll(){
        this.change(this.state.allAmount)
        this.setState({
            trail:false,
            backAll:true,
            amount:this.state.allAmount,
            totalRedemptionIndex: 1,
        })
    }
    change(value){
        if (value && value<=this.state.allAmount) {
            axios({
                method:"GET",
                url:"http://39.101.141.248:9527/transaction/trialCalculation",
                params:{
                    comBaseId:this.props.comBaseId,
                    amount:value,
                },
            }).then(res=>{
                if(res.data.code === 200){
                    this.setState({
                        amount:value,
                        redBoolen:true,
                        trial:true,
                        trialCalculationList:res.data.trialCalculationList,
                    })
                }
            }).catch(error=>{
                console.log(error);
            });
        } else { //不满足起购金额，提示错误
            /* Toast.info("购买金额不得低于100,00万元")  一键买入组合时，您的购买金额会自动根据管理人的持仓配比和在途交易调整至最合适的配比。*/
            this.setState({
                amount:"",
                redBoolen:false,
                trial:false,
            })
        }
    }
    //输入框清除
    onClear(e){
        this.setState({
            trial:false,
            amount:"",
            backAll:false,
        })
    }
    //赎回确认提示
    onSubmit(){
        alert(
            "交易提示",
            "组合适合长期投资，您是否确定赎回？",
            [
                {text:'暂不赎回',onPress:()=>console.log("暂不赎回")},
                {text:'确认赎回',onPress:()=> this.buyBack()},
            ])
    }
    //赎回函数
    buyBack(){
        axios({
            method:"GET",
            url:"http://39.101.141.248:9527/transaction/redemption",
            params:{
                userId:getCookieId(),
                comBaseId:this.props.comBaseId,
                totalRedemptionIndex:this.state.totalRedemptionIndex,
                amount:this.state.amount,
            },
        }).then(res=>{
            var data = res.data;
            if(res.data.code === 200){
                var path = {
                    pathname:'/buyBackResult',
                    query:data,
                }
                alert(
                    "申请成功",
                    (
                        <Result
                            img= {<img src={require("../../../access/images/success.png")} style={{width:100,height:100,textAlign:"center",marginLeft:-10,marginTop:-30,marginBottom:200}}/>}
                        />
                    ),
                    [
                        {text:'确定',onPress:()=>this.props.history.push(path)},
                    ])
            }
        }).catch(error=>{
            console.log(error);
        });
    }
    render() {
       const {getFieldProps, getFieldError} = this.props.form;
        return(
            <form>
                <Card full>
                    <Card.Header
                        title={this.props.comBaseName}
                       /* extra={ <Tag style={{color:"#f8a83f"}}> 基金型</Tag>}*/
                    />
                    <Card.Body>
                        <span style={{color:"darkgray"}}>可赎回：{this.state.allAmount}元</span>
                    </Card.Body>
                    {/*<Card.Footer content="到账账户：我的钱包"/>*/}
                </Card>
                <WhiteSpace size="lg"/>
                <List>
                    <Item>
                        <span style={{float:'left',fontSize:15,color:"darkgray"}}>赎回份额</span>
                        <Link to="/combineDealRule">
                        <span style={{float:'right',fontSize:13,color:"#f8a83f"}}>交易规则</span>
                        </Link>
                    </Item>
                    <Item>
                        <div style={{width:"85%",float:"left"}}>
                            {
                                !this.state.backAll?(<InputItem
                                {...getFieldProps('money2', {
                                    // 输入小数点后最多三位
                                    normalize: (v, prev) => {
                                        if (v && !/^(([1-9]\d*)|0)(\.\d{0,3}?)?$/.test(v)) {
                                            if (v === '.') {
                                                return '0.';
                                            }
                                            return prev;
                                        }
                                        return v;
                                    },
                                    rules: [
                                        { required: true, message: '请输入赎回金额！' },
                                        { validator: this.validateMoney.bind(this) },
                                    ],
                                })}
                                error={!!getFieldError('money2')}
                                onErrorClick={() => {
                                    Toast.info("赎回金额不得高于持仓金额")
                                }}
                             /*   value={this.state.amount}*/
                                type={'money'}
                                placeholder={<span>最多可赎回{this.state.allAmount}元</span>}
                                onVirtualKeyboardConfirm={v => console.log(v)}
                                clear
                                style={{float:"left"}}
                                moneyKeyboardWrapProps={moneyKeyboardWrapProps}
                            >{<span style={{fontSize:28}}>¥</span>}
                            </InputItem>
                                ):null}
                            {
                                this.state.backAll?(<InputItem
                                    {...getFieldProps('money2', {
                                        // 输入小数点后最多三位
                                        normalize: (v, prev) => {
                                            if (v && !/^(([1-9]\d*)|0)(\.\d{0,3}?)?$/.test(v)) {
                                                if (v === '.') {
                                                    return '0.';
                                                }
                                                return prev;
                                            }
                                            return v;
                                        },
                                        rules: [
                                            { required: true, message: '请输入购买金额！' },
                                            { validator: this.validateMoney.bind(this) },
                                        ],
                                    })}
                                    value={this.state.amount}
                                    error={!!getFieldError('money2')}
                                    onErrorClick={() => {
                                        Toast.info("购买金额不得低于起购金额")
                                    }}
                                    /*   value={this.state.amount}*/
                                    type={'money'}
                                    placeholder={"最多可赎回10000000元"}
                                    onVirtualKeyboardConfirm={v => console.log(v)}
                                    clear
                                    style={{float:"left"}}
                                    moneyKeyboardWrapProps={moneyKeyboardWrapProps}
                                >{<span style={{fontSize:28}}>¥</span>}
                                </InputItem>):null}
                        </div>
                    <div onClick={this.backAll.bind(this)} style={{marginTop:10,fontSize:13,color:"#f8a83f",width:"15%",textAlign:"right",float:"right"}}>
                            全部赎回
                    </div>
                    </Item>
                </List>
                <WhiteSpace size="lg"/>
                    {
                        !this.state.trial ?(
                            this.state.combinatiobShares.map((item, index) => {
                                return (
                                    <Item  wrap key={item.proTsCode}>
                                        <div className="font3" style={{float:"left",marginTop:-20,height:40}}>
                                            <p style={{marginTop:10,fontSize:16}}>{item.proName}</p>
                                            <p className="gray-text" style={{textAlign:"left"}}>{item.proTsCode}</p>
                                        </div>
                                        <div className="my-list-item2" >--</div>
                                        {/* {getFieldDecorator('list1')(
                                            <InputItem/>)}*/}
                                    </Item>
                                )
                            })
                        ):null
                    }
                {
                    this.state.trial?(
                        this.state.trialCalculationList.map((item, index) => {
                            return (
                                <Item  wrap key={item.proTsCode}>
                                    <div>
                                        <div className="font3" style={{float:"left",marginTop:-20,height:40}}>
                                            <p style={{marginTop:10,fontSize:16}}>{item.proName}</p>
                                            <p className="gray-text" style={{textAlign:"left"}}>{item.proTsCode}</p>
                                        </div>
                                        <div className="font3" style={{float:"right",marginTop:-20,height:40}}>
                                            <p style={{marginTop:10,fontSize:16}}>{item.amount}</p>
                                            <p className="gray-text" style={{textAlign:"right"}}>{item.ratio}</p>
                                        </div>
                                    </div>
                                </Item>
                            )
                        })
                    ):null
                }
                <li style={{marginLeft:15,color:"darkgray",fontSize:12}}>产品过往业绩不预示其未来表现，市场有风险，投资需谨慎</li>
                <WhiteSpace size="lg"/>
                <WhiteSpace size="lg"/>
                <Button onClick={this.onSubmit.bind(this)} style={{width:"90%",backgroundColor:"#f8a83f",color:"white",margin:"0 auto"}}>确定</Button>
            </form>
        )
    }
}
